#include "KPF_HttpSession.h"


KPF_HttpSession::KPF_HttpSession( const int8_t *pIP, const int16u_t iPort )
	: m_IP( (char *)pIP ), m_iPort(iPort)
{
	CSessionParam stSessionParam;
	
	memset( &stSessionParam, 0x00, sizeof(stSessionParam) );
	memcpy( stSessionParam.pIP, (char *)pIP, strlen( (char *) pIP) + 1 );
	stSessionParam.iPort = iPort;
	
	pm_Session = create_session( SESSION_TYPE_HTTP_CLIENT, &stSessionParam );
	if ( pm_Session )
	{
		
		if ( set_session_business( pm_Session, onSessionBusiness, this ) >= 0 )
		{
			if ( set_session_event( pm_Session, onSessionEvent ) >= 0 )
			{
				//log_print( (int8_t *)"create tcp session ok................" );
			}
		}
	}
	else 
		log_print( (int8_t *)"create udp session failed????????????????????????" );
}
	
KPF_HttpSession::~KPF_HttpSession( void )
{
	
}

int32_t KPF_HttpSession::handle_input( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	if ( pData )
	{
		CHttpData *pHttpData = (CHttpData *)pData;
		
		if ( pHttpData )
		{
			//fwrite( pHttpData->pHttpData, 1, pHttpData->iCurrentHttpDataLen, pHandle );
			//fflush( pHandle );
			
			//log_print( "pHttpData->iCurrentHttpDataLen-->%d", pHttpData->iCurrentHttpDataLen );
			fwrite( pHttpData->pHttpData, 1, pHttpData->iCurrentHttpDataLen, stdout );
			fflush( stdout );
		}
		
		iRetCode = 0;
	}
	
	return iRetCode;	
}

int32_t KPF_HttpSession::handle_output( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	CHttpData stHttpData;
	char *pPeerIP = (char *)m_IP.c_str(  );
	char *pURL = (char *)"/business/api/punch.php";
				
	memset( &stHttpData, 0x00, sizeof(stHttpData) );
	stHttpData.pHost = (int8_t *)pPeerIP;
	stHttpData.pURL = (int8_t *)pURL;
	stHttpData.eHttpAction = SESSION_HTTP_GET;

	while ( 1 )
	{
		iRetCode = send_session_data( pm_Session, (int8u_t *)&stHttpData, sizeof(stHttpData), NULL );
		
		//log_print( (int8_t *)"pPeerIP-->%s, m_iPort-->%d, iRetCode-->%d", pPeerIP, m_iPort, iRetCode );
						
		os_sleep( 1000 * 2);
	}
	
	return iRetCode;	
}
	
int32_t KPF_HttpSession::handle_event( const KPF_Event &eEvent )
{
	int32_t iRetCode = -1;
	
	//log_print( (int8_t *)"http_session: handle_event------------------>" );
	
	if ( EVENT_READ_ERROR == ((KPF_Event)eEvent).getEvent() )
		iRetCode = remove_session_socket( pm_Session, ((KPF_Event)eEvent).getEventParam().pSocket );
	
	return iRetCode;	
}
